# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from WebBase import Base

class Index(Base):

    @view_config(route_name='AppWebRedirectRoute', request_method='GET')
    def AppWebRedirectRoute(self):
        url = self.request.params['url']
        if url.startswith("http"):
            pass
        else:
            url = "http://" + url
        return HTTPFound(location=url);


    @view_config(route_name='AppWebIndexSimpleRoute', renderer='../../templates/AppWebIndexSimple.pt')
    def AppWebIndexSimpleRoute(self):
        print self.request.session
        if self.request.session:
            pass
        else:
            return HTTPFound(location='/')
        tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            csc = self.request.session['csc']
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait}
        return map

    @view_config(route_name='AppWebIndexRoute', renderer='../../templates/AppWebIndex.pt')
    def AppWebIndexRoute(self):
        tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            #portrait = self.request.session['portrait'].replace('/media', '/static')
            csc = self.request.session['csc']
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        selectSQL = '''
            SELECT username, tel, email, portrait
                FROM user_info
                WHERE tel = %s;
        '''
        result = MySqlCRUD.selectImpl(selectSQL, tel)
        tel = result[0]['tel']
        username = result[0]['username']
        email = result[0]['email']
        portrait = result[0]['portrait'].replace('/media', '/static')
        self.request.session['tel'] = tel
        self.request.session['username'] = username
        self.request.session['email'] = email
        self.request.session['portrait'] = portrait
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait}
        return map

    @view_config(route_name='AppWebBgImgIndexRoute', renderer='../../templates/AppWebBgImgIndex.pt')
    def AppWebBgImgIndexRoute(self):
        tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            #portrait = self.request.session['portrait'].replace('/media', '/static')
            csc = self.request.session['csc']
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        selectSQL = '''
            SELECT username, tel, email, portrait
                FROM user_info
                WHERE tel = %s;
        '''
        result = MySqlCRUD.selectImpl(selectSQL, tel)
        tel = result[0]['tel']
        username = result[0]['username']
        email = result[0]['email']
        portrait = result[0]['portrait'].replace('/media', '/static')
        self.request.session['tel'] = tel
        self.request.session['username'] = username
        self.request.session['email'] = email
        self.request.session['portrait'] = portrait
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait}
        return map

